package h0718;

import h0706.UnionFindSet;

import java.util.Arrays;
import java.util.Scanner;

/**
 * @author 不知名帅哥
 * @version 1.0
 * @description 精准核酸检测
 * @date 2024/7/18 9:02
 */
public class AccurateNucleicAcidTesting {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt(); //总人数
        sc.nextLine();
        int[] dignosed = Arrays.stream(sc.nextLine().split(","))
                .mapToInt(Integer::parseInt).toArray();  //已经确诊的
        UnionFindSet set = new UnionFindSet(n);  //从0开始
        for (int i = 0; i < dignosed.length - 1; i++) {
            set.union(dignosed[i], dignosed[i + 1]);   //合并
        }
        int parent = set.findParent(dignosed[0]);

        int[][] persons = new int[n][n];
        for (int i = 0; i < n; i++) {  //用二维数组第二位表示已经确诊的
            persons[i] = Arrays.stream(sc.nextLine().split(",")).mapToInt(Integer::parseInt).toArray();
        }

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < i + 1; j++) {
                if (persons[i][j] == 1) {  //证明有接触
                    set.union(i, parent);   //合并为一个集合
                }
            }
        }
        int count = 0;
        for (int i = 0; i < n; i++) {
            if (set.findParent(i) == parent) {  //判断是否同一个祖先
                count++;
            }
        }
        System.out.println(count- dignosed.length); //需要减去原有的已经确诊的人数。
    }
}

